layui.config({
    base: path + '/layuiadmin/' //静态资源所在路径
}).extend({
    index: 'lib/index' //主入口模块
}).use(['index', 'table'], function () {
    var table = layui.table
        , admin = layui.admin
        , $ = layui.$
        , form = layui.form;

    /**
     * 表格数据初始化
     */
    table.render({
        elem: '#userTable'
        , url: path + '/main/user/getUsers.json'
        , height: 500
        , limit: 10
        , loading: true
        , cols: [[
            {field: 'id', width: 80, title: 'ID', sort: true, fixed: 'left', align: 'center'}
            , {field: 'userName', width: 150, title: '用户名', sort: true, align: 'center'}
            , {field: 'nickName', width: 150, title: '用户昵称', sort: true, align: 'center'}
            , {field: 'roleNames', width: 150, title: '用户角色', sort: true, align: 'center'}
            , {field: 'age', width: 150, title: '年龄', sort: true, align: 'center'}
            , {field: 'sex', width: 150, title: '性别', sort: true, align: 'center'}
            , {field: 'email', width: 200, title: '邮箱', align: 'center'}
            , {field: 'phone', width: 200, title: '手机号码', sort: true, align: 'center'}
            , {field: 'lastLoginTime', minWidth: 200, title: '最近登录时间', sort: true, align: 'center'}
            , {width: 200, align: 'center', title: '操作', toolbar: '#userTable-barDemo'}
        ]]
        , page: true
        , done: function (obj) {
            if (obj.data.length == 0) {
                $(".layui-table-main .layui-none").text("未查询到数据!")
            }
        }
        , text: '对不起，加载出现异常！'
    });

    /**
     * 监听搜索
     */
    form.on('submit(searchTable)', function (data) {
        var field = data.field;
        //执行重载
        table.reload('userTable', {
            where: field,
            page: '{"curr":1}'
        });
    });

    /**
     * 监听工具条
     */
    table.on('tool(userTable)', function (obj) {
        var data = obj.data;
        var thisUserId = data.userId;
        if (obj.event === 'detail') {
            $.ajax({
                url: path + "/main/user/getOneUserInfo.json",
                type: "GET",
                dataType: "JSON",
                data: {"userId": data.userId},
                success: function (obj) {
                    console.log(obj)
                    window.userObj = obj;
                    if (obj != "") {
                        layer.open({
                            type: 2
                            , title: '<span style="font-weight: bold">查看用户[' + obj.userInfo.userName + ']详细信息<span>'
                            , content: path + '/main/user/lookUserInfo.html'
                            , maxmin: false
                            , area: ['100%', '100%']
                            , anim: 2
                            , resize: false
                            , btn: ['返回']
                            , data: obj
                        });
                    }
                },
                error: function () {
                    layer.msg('查看用户信息接口异常,请联系开发者！');
                }
            });
        } else if (obj.event === 'del') {
            if (thisUserId == userId) {
                layer.msg('不能删除自己哦！如需进行操作,请前往<a href="javascript:;" style="color: deepskyblue">【安全中心】</a>进行注销账户操作！');
            } else {
                layer.confirm('确认删除用户<span style="color: deepskyblue">【' + data.userName + '】</span>吗？', function (index) {
                    var loadIcon = layer.load(0, {
                        shade: true,
                        time: false,
                        shade: [0.1,'#fff']
                    });
                    /*删除*/
                    $.ajax({
                        url: path + "/main/user/delUserInfo.json",
                        type: "DELETE",
                        dataType: "JSON",
                        data: {"userId": data.userId},
                        success: function (data) {
                            layer.close(loadIcon);
                            if (data.code == "0") {
                                layer.msg("删除用户信息成功!", {
                                    icon: 1,
                                    time: 2000
                                });
                            } else {
                                layer.msg("删除用户信息失败!", {
                                    icon: 2,
                                    time: 2000
                                });
                            }
                        },
                        error: function () {
                            layer.close(loadIcon);
                            layer.msg('删除用户接口异常,请联系开发者！');
                        }
                    });
                    obj.del();
                    layer.close(index);
                });
            }
        } else if (obj.event === 'edit') {
            $.ajax({
                url: path + "/main/user/getOneUserInfo.json",
                type: "GET",
                dataType: "JSON",
                data: {"userId": data.userId},
                success: function (obj) {
                    window.userObj = obj;
                    if (obj != "") {
                        layer.open({
                            type: 2
                            , title: '<span style="font-weight: bold">修改用户[' + obj.userInfo.userName + ']基本信息<span>'
                            , content: path + '/main/user/modifyUserForm.html'
                            , maxmin: false
                            , area: ['100%', '100%']
                            , anim: 2
                            , resize: false
                            , btn: ['确定','返回']
                            , data: obj
                            , yes: function (index, layero) {
                                var iframeWindow = window['layui-layer-iframe' + index]
                                    , submitID = 'modify-User-Submit'
                                    , submit = layero.find('iframe').contents().find('#' + submitID);
                                /**
                                 * 监听提交
                                 */
                                iframeWindow.layui.form.on('submit(' + submitID + ')', function (data) {
                                    var loadIcon = layer.load(0, {
                                        shade: true,
                                        time: false,
                                        shade: [0.1,'#fff']
                                    });
                                    /*获取提交的字段*/
                                    var jsonStr = data.field;
                                    /*执行ajax操作*/
                                    $.ajax({
                                        url: path + "/main/user/editUserInfo.json",
                                        type: "PUT",
                                        dataType: "JSON",
                                        data: jsonStr,
                                        success: function (data) {
                                            layer.close(loadIcon);
                                            if (data.code == "success") {
                                                console.log(thisUserId+"////"+userId);
                                                if(thisUserId == userId){
                                                    layer.open({
                                                        type: 1
                                                        ,id: 'editThisLogout'
                                                        ,content: '<div style="padding: 20px 100px;">当前用户信息已修改,点击重新登录</div>'
                                                        ,btn: '确定'
                                                        ,btnAlign: 'c'
                                                        ,shade: [0.1,'#fff']
                                                        ,yes: function(){
                                                            layer.closeAll();
                                                            top.location = path+"/logout";
                                                            // window.location.href = path+"/logout";
                                                        }
                                                    });
                                                }else{
                                                    layer.close(index);
                                                    layer.msg("修改用户信息操作成功！");
                                                    /*刷新*/
                                                    table.reload('userTable', {
                                                        where: '{userName: ""}',
                                                        page: '{"curr":1}'
                                                    });
                                                }
                                            } else {
                                                layer.msg("修改用户信息失败！");
                                            }
                                        },
                                        error: function () {
                                            layer.close(loadIcon);
                                            layer.msg('修改用户接口异常,请联系开发者！');
                                        }
                                    });
                                });
                                submit.trigger('click');
                            }
                        });
                    }
                },
                error: function () {
                    layer.msg('修改用户信息接口异常,请联系开发者！');
                }
            });
        }
    });

    /**
     * 监听新增按钮
     */
    var $ = layui.$, active = {
        addUser: function () {
            layer.open({
                type: 2
                , title: '<span style="font-weight: bold">新增用户信息</span>'
                , content: path + '/main/user/addUser.html'
                , maxmin: false
                , area: ['100%', '100%']
                , anim: 2
                , btn: ['确定', '返回']
                , yes: function (index, layero) {
                    var iframeWindow = window['layui-layer-iframe' + index]
                        , submitID = 'add-User-Submit'
                        , submit = layero.find('iframe').contents().find('#' + submitID);
                    /**
                     * 监听提交
                     */
                    iframeWindow.layui.form.on('submit(' + submitID + ')', function (data) {
                        /*获取提交的字段*/
                        var jsonStr = data.field;
                        $.ajax({
                            url: path + "/main/user/checkedUserName.json",
                            type: "GET",
                            dataType: "JSON",
                            data: {"userName": jsonStr.userName},
                            success: function (data) {
                                if (data.isExist == "1") {
                                    layer.msg("请按照页面提示完善表单【用户名重复】");
                                } else {
                                    if (jsonStr.passWord.length>=6){
                                        if (jsonStr.passWord!=jsonStr.rePassWord){
                                            layer.msg("请按照页面提示完善表单【两次输入的密码不一致】");
                                        } else {
                                            var loadIcon = layer.load(0, {
                                                shade: true,
                                                time: false,
                                                shade: [0.1,'#fff']
                                            });
                                            /*执行ajax操作*/
                                            $.ajax({
                                                url: path + "/main/user/addUserInfo.json",
                                                type: "POST",
                                                dataType: "JSON",
                                                data: jsonStr,
                                                success: function (data) {
                                                    layer.close(loadIcon);
                                                    if (data.code == "0") {
                                                        layer.close(index);
                                                        layer.msg("新增用户信息操作成功！");
                                                        /*刷新*/
                                                        table.reload('userTable', {
                                                            where: '{userName: ""}',
                                                            page: '{"curr":1}'
                                                        });
                                                    } else {
                                                        layer.msg("新增用户信息失败！");
                                                    }
                                                },
                                                error: function () {
                                                    layer.close(loadIcon);
                                                    layer.msg('新增用户接口异常,请联系开发者！');
                                                }
                                            });
                                        }
                                    } else {
                                        layer.msg("请按照页面提示完善表单【密码长度应大于6位】");
                                    }
                                }
                            },
                            error: function () {
                                layer.msg('检查用户名接口异常,请联系开发者！');
                            }
                        });
                    });
                    submit.trigger('click');
                }
            });
        }
    };

    /**
     * 监听按钮点击
     */
    $('.userTable-btn .layui-btn').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });

});